package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass =MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Override
    public List<Menu> getAllMenu() {
        List<Menu> firstMenus=menuMapper.selectFirstMenu();
        for (Menu firstMenu : firstMenus) {
            List<Menu> secondMenus=menuMapper.selectByParentId(firstMenu.getId());
            firstMenu.setChildren(secondMenus);
        }
        return firstMenus;
    }

    @Override
    public void add(Menu menu) {
        Integer parentMenuId = menu.getParentMenuId();
        //根据父id找到所有的父菜单下的所有子菜单的数量
        int childCount=menuMapper.selectCountByParentId(parentMenuId);
        //priority
        int priority=childCount+1;
        menu.setPriority(priority);
        //拼接path
        Menu parentMenu = menuMapper.selectByPrimaryKey(parentMenuId);
        String parentPath=null;
        int parentMenuLevel = parentMenu.getLevel();
        if (parentMenuLevel==1){
            parentPath= "/"+parentMenu.getPath();
        }else {
            parentPath=parentMenu.getPath();
        }
        String path=parentPath+"-"+priority;
        menu.setPath(path);
        //获取父级别+1
        int level=parentMenuLevel+1;
        menu.setLevel(level);

        menuMapper.insert(menu);

    }

    @Override
    public void delete(Integer id) {
        menuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Menu findById(Integer id) {
        Menu menu = menuMapper.selectByPrimaryKey(id);
        return menu;
    }

    @Override
    public void edit(Menu menu) {
        menuMapper.updateByPrimaryKeySelective(menu);
    }
}
